#!/bin/bash


LOGFILE=/tmp/vm_ops.log
function LOG_MSG()
{
echo "[`date "+%Y/%m/%d %H:%M:%S"`] $*" >> $LOGFILE
}

function wait_iso_to_be_attatched(){
counter=0
while :; do
    LOG_MSG "check dom %vm_id if be iso attached"
    flag=`/usr/bin/xenstore-read iso_attach`
    if [ $flag == '1' ];then
        LOG_MSG "iso has attached"
        break;
    fi
    sleep 1
    counter=`expr $counter + 1`
    if [ $counter -eq 200 ];then
        LOG_MSG "domU wait iso attached timeout"
        return 1;
    fi
    sleep 1
done
}

function notify_vm_iso_deattached(){
/usr/bin/xenstore-write iso_attach 2
if [ $? -ne 0 ];then
   LOG_MSG "xenstore write error"
   return 1;
fi
}

function set_hostname(){
  hostname $1
} 
function set_password(){
passwd <<EOF
$1
$1
EOF
}

function set_ipaddr0(){
ifconfig eth1 $1 
}

function set_ipaddr1(){
ifconfig eth2 $1
}

function set_ipaddr2(){
ifconfig eth3 $1
}


function do_sence(){
wait_iso_to_be_attatched
if [ $? -ne 0 ];then
   LOG_MSG "wait iso attached failed"
   return 1;
fi
mount -o loop /dev/xvdb1 /mnt
cat /mnt/initialize | while read name value
do
    echo $name $value
    case $name in 
    hostname) set_hostname $value ;;
    password) set_password $value ;;
    ipaddr0)   set_ipaddr0 $value;;
    ipaddr1)   set_ipaddr1 $value;;
    ipaddr2)   set_ipaddr2 $value;;	
    esac
done
umount /mnt

mount -t nfs -o nolock 172.18.218.100://root/xen/vms_work_dir/ip_maps /mnt
lan_ip=`/sbin/ifconfig eth0|grep 'inet addr'|awk '{print$2}'|cut -d: -f2`
subnet_ip=`/sbin/ifconfig eth1|grep 'inet addr'|awk '{print$2}'|cut -d: -f2`
echo $lan_ip >> /mnt/$subnet_ip;
umount /mnt

notify_vm_iso_deattached
}

do_sence 
rm /vm_scene.sh  









